package com.haoze.nurseapp.service.impl;

import com.haoze.common.config.RedisUtil;
import com.haoze.nurseapp.service.feign.JwtService;
import com.haoze.nurseapp.vo.UserInfoVO;
import com.haoze.nurseapp.model.UserEntity;
import com.haoze.nurseapp.dao.UserMapper;
import com.haoze.nurseapp.service.UserService;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    UserMapper userMapper;

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    JwtService jwtService;

    @Override
    public Result login(UserEntity user) {
        if (user.getLoginName() == null) {
            return ResultGenerator.genFailedResult("账号不能为空");
        }
        if (user.getUserPwd() == null) {
            return ResultGenerator.genFailedResult("密码不能为空");
        }
        // 用户名登录
        UserEntity dbUser = null;
        if (user.getLoginName() != null) {
            dbUser = userMapper.queryOneUser(user.getLoginName());
            if (dbUser == null) {
                return ResultGenerator.genFailedResult("账号不存在");
            } else if (StateEnum.EMR_STOP.getValue().equals(dbUser.getLockFlag())) {
                return ResultGenerator.genFailedResult("账号被停用");
            } else if (StateEnum.EMR_DEL.getValue().equals(dbUser.getDelFlag())) {
                return ResultGenerator.genFailedResult("账号被删除");
            }
        }
        // 验证密码
        if (!verifyPassword(user.getUserPwd(), dbUser.getUserPwd())) {
            return ResultGenerator.genFailedResult("密码错误");
        }
        user.setUserId(dbUser.getUserId());
        Result result = getToken(user, StateEnum.LOGIN.getValue());
        redisUtil.set(String.valueOf(result.getData()), user.getLoginName(),72L, TimeUnit.HOURS);
        return result;
    }

    /**
     * 获得 token
     */
    private Result getToken(final UserEntity user, String type) {
        final String username = user.getLoginName();
        final String id = user.getUserId();
        final String token = jwtService.getToken(username, id, "1","MOBILE");
        //final String token = jwtService.getToken(username, id, "1");
        /*if (StateEnum.LOGIN.getValue().equals(type))
            redisUtil.set(id,token,60*30);*/
        return ResultGenerator.genOkResult(token);
    }

    @Override
    public boolean verifyPassword(final String rawPassword, final String encodedPassword) {
        return this.passwordEncoder.matches(rawPassword, encodedPassword);
    }

    @Override
    public Result getUserInfo(String account) {

        Map<String, Object> map = userMapper.queryUserInfo(account);
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setName(map.get("name").toString());
        userInfoVO.setDept(map.get("dept").toString());
        userInfoVO.setPosition(map.get("position")==null?"":map.get("position").toString());
        userInfoVO.setEmail(map.get("email")==null?"":map.get("email").toString());
        userInfoVO.setRole(map.get("role")==null?"":map.get("role").toString());
        return ResultGenerator.genOkResult(userInfoVO);
    }

    @Override
    public UserEntity getUserByAccount(String account) {
        return userMapper.queryOneUser(account);
    }

    @Override
    public Result updateClinetIdByAccount(String account, String clientId) {
        //先清除clientId对应的其他人,再对该用户进行设置
        userMapper.updateClinetIdByClinetId(clientId);
        int isSuccess = userMapper.updateClinetIdByAccount(account, clientId);
        if(isSuccess==0) {
            return ResultGenerator.genFailedResult("记录clientId失败");
        }else{
            return ResultGenerator.genOkResult();
        }
    }


}
